<script setup>
import {
  Promotion,
  Mute,
  Microphone,
  Switch
} from '@element-plus/icons-vue'
import { onMounted, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import useStomp from '@/utils/stomp'
import { useUserStore } from '@/stores'
import { liveGetProductService, liveGetRoomProductService } from '@/api/live'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore();
const baseURL = import.meta.env.VITE_WS_BASE_URL

// 接收 PRODUCT 事件回调
const productEventCallback = async (content) => {
  const res = await liveGetProductService(content);
  products.value.unshift(res.data.data);
}

const explainEventCallback = (content) => {
  currentProductId.value = content;
}

const handleStompMessage = (message) => {
  const {type, content} = JSON.parse(message.body);
  if (type === 'CHAT') {
    const contentObj = JSON.parse(JSON.parse(message.body).content);
    contentObj['time'] = new Date().toLocaleDateString();
    messageArray.value.push(contentObj);
  } else if (type === 'PRODUCT') {
    productEventCallback(content);
  } else if (type === 'EXPLAIN') {
    explainEventCallback(content);
  }
}

// WebSocket
const { connect, isConnected, messageArray, subscribe, send } = useStomp(`${baseURL}/live/api/me/ws?token=Bearer ${userStore.token}`, handleStompMessage);
const newMessage = ref('')
const chatUsers = ref(0)

// RTC配置
const srsIp = "106.13.105.230"
const rtcConfig = {
  // iceServers: [
  //   { 
  //     urls: "stun:47.121.24.225:3478"
  //   },
  //   {
  //     urls: 'turn:47.121.24.225:3478',
  //     username: "yixuan",
  //     credential: "qq2434462503"
  //   }
  // ]
};

// 直播相关状态
const roomId = route.query.roomId;
const isMuted = ref(true) // 默认静音
const videoElement = ref(null)
const rtcPeerConnection = ref(null)
const isPlaying = ref(false)
const connectionState = ref('disconnected')

// 商品相关状态
const products = ref([
])
const getProducts = async () => {
  products.value = (await liveGetRoomProductService(roomId)).data.data;
}
getProducts();
const currentProductId = ref(2) // 当前讲解的商品ID

// 计算当前展示的商品
const currentProduct = computed(() => {
  return products.value.find(p => p.id === currentProductId.value)
})

// 初始化WebRTC播放
const initWebRTCPlay = async () => {
  try {
    connect(`/topic/room.${roomId}`);
    connectionState.value = 'connecting'
    
    // 创建RTCPeerConnection
    rtcPeerConnection.value = new RTCPeerConnection(rtcConfig)
    
    // 处理收到的媒体流
    rtcPeerConnection.value.ontrack = (event) => {
      if (videoElement.value) {
        if (!videoElement.value.srcObject) videoElement.value.srcObject = new MediaStream();
        videoElement.value.srcObject.addTrack(event.track);
        videoElement.value.play()
        isPlaying.value = true
        connectionState.value = 'connected'
      }
    }
    
    // ICE候选处理
    rtcPeerConnection.value.onicecandidate = (event) => {
      if (event.candidate) {
        // 发送ICE候选到信令服务器（实际应用中需要实现）
        console.log('New ICE candidate:', event.candidate)
      }
    }
    
    // 连接状态变化
    rtcPeerConnection.value.onconnectionstatechange = () => {
      connectionState.value = rtcPeerConnection.value.connectionState
      console.log('Connection state:', connectionState.value)
    }
    
    // 创建Offer
    const offer = await rtcPeerConnection.value.createOffer({
      offerToReceiveAudio: true,
      offerToReceiveVideo: true
    })
    
    await rtcPeerConnection.value.setLocalDescription(offer)
    
    // 发送Offer到SRS的API（拉流地址）
    const streamUrl = `webrtc://${srsIp}:1990/live/${roomId}`
    const apiUrl = `http://${srsIp}:1985/rtc/v1/play/`
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        sdp: offer.sdp,
        streamurl: streamUrl,
        api: apiUrl,
        clientip: null
      })
    })
    
    const answer = await response.json()
    
    // 设置SRS返回的Answer为远程描述
    await rtcPeerConnection.value.setRemoteDescription(
      new RTCSessionDescription({ type: 'answer', sdp: answer.sdp })
    )
    
    console.log('WebRTC play initialized successfully')
  } catch (error) {
    console.error('WebRTC play initialization failed:', error)
    connectionState.value = 'failed'
  }
}

// 切换静音状态
const toggleMute = () => {
  if (videoElement.value) {
    videoElement.value.muted = !videoElement.value.muted
    isMuted.value = videoElement.value.muted
  }
}

// 发送消息
const sendChatMessage = () => {
  if (newMessage.value.trim()) {
    
    send(`/app/global/${roomId}`, {type: 0, content: newMessage.value});
    newMessage.value = '';
  }
}

// 离开直播间
const leaveLiveRoom = () => {
  if (rtcPeerConnection.value) {
    rtcPeerConnection.value.close()
  }
  router.back();
}

// 模拟收到的消息（实际应用从WebSocket接收）
const systemMessage = {
  id: 1,
  type: 'system',
  content: '欢迎来到直播间！',
  sender: '系统',
  timestamp: new Date().toISOString()
}

// 初始化
onMounted(() => {
  // 模拟连接WebSocket
  setTimeout(() => {
    // 加入房间后收到系统消息
    messageArray.value.push(systemMessage)
    
    // 模拟在线人数变化
    chatUsers.value = Math.floor(Math.random() * 1000) + 50
  }, 1000)
  
  // 初始化WebRTC播放
  initWebRTCPlay()
})
</script>

<template>
  <div class="live-container">
    <!-- 顶部导航 -->
    <div class="live-header">
      <div class="brand" @click="router.back()">YH</div>
      <div class="live-status">
        <span class="status-indicator live"></span>
        {{ connectionState === 'connected' ? '直播中' : connectionState }}
      </div>
      <div class="user-count">
        <i class="el-icon-user"></i>
        在线观众: {{ chatUsers.toLocaleString() }}
      </div>
      <el-button 
        class="leave-btn" 
        type="danger" 
        plain 
        @click="leaveLiveRoom"
      >
        <el-icon><Switch></Switch></el-icon> 离开直播间
      </el-button>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧直播区 -->
      <div class="video-section">
        <div class="video-container">
          <video 
            ref="videoElement" 
            autoplay 
            playsinline 
            muted
            class="video-preview"
          ></video>
          
          <div v-if="!isPlaying" class="loading-overlay">
            <div class="spinner"></div>
            <div class="loading-text">连接直播中...</div>
          </div>
          
          <div class="overlay-info">
            <div class="viewer-count">
              <i class="el-icon-user-solid"></i> {{ chatUsers.toLocaleString() }} 人正在观看
            </div>
            <div class="current-product" v-if="currentProduct">
              正在讲解: {{ currentProduct.name }}
            </div>
          </div>
          
          <!-- 播放控制 -->
          <div class="play-controls">
            <el-button 
              circle 
              :type="isMuted ? '' : 'info'" 
              @click="toggleMute"
              class="control-btn"
            >
              <el-icon v-if="isMuted"><Mute /></el-icon>
              <el-icon v-else><Microphone /></el-icon>
            </el-button>
          </div>
        </div>
        
        <!-- 商品列表 -->
        <div class="product-list">
          <h3>直播商品 <el-tag type="info" size="small">当前讲解商品已高亮</el-tag></h3>
          <div class="products">
            <div 
              v-for="product in products" 
              :key="product.id"
              class="product-card"
              :class="{ active: currentProductId === product.id }"
            >
              <img :src="product.imageUrl" alt="商品图片">
              <div class="product-info">
                <div class="name">{{ product.name }}</div>
                <div class="price">¥{{ product.price }}</div>
                <div class="sales">库存: {{ product.stock }}件</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧聊天区 -->
      <div class="chat-section">
        <div class="chat-header">
          <i class="el-icon-chat-line-round"></i>
          直播间聊天
          <el-tag type="success" size="small">{{ chatUsers.toLocaleString() }}人在线</el-tag>
        </div>
        
        <div class="chat-messages">
          <div 
            v-for="message in messageArray" 
            :key="message.id"
            class="message"
            :class="message.type"
          >
            <div class="message-header">
              <span class="username">{{ message.name }}</span>
              <span class="timestamp">{{ message.time }}</span>
            </div>
            <div class="content">{{ message.content }}</div>
          </div>
        </div>
        
        <div class="chat-input">
          <el-input 
            v-model="newMessage" 
            placeholder="输入消息..."
            @keyup.enter="sendChatMessage"
          >
            <template #append>
              <el-button 
                type="primary" 
                :icon="Promotion" 
                @click="sendChatMessage"
              >
                发送
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>
    
    <!-- 底部状态栏 -->
    <div class="live-footer">
      <div class="current-time">
        <i class="el-icon-time"></i> {{ new Date().toLocaleTimeString() }}
      </div>
      <div class="connection-status">
        <i class="el-icon-connection"></i>
        直播状态: {{ connectionState }}
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.live-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #0f0f13;
  color: #e0e0e0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  overflow: hidden;
}

.live-header {
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background: linear-gradient(90deg, #1a1c2b, #222538);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  border-bottom: 1px solid #2d3045;
  
  .brand {
    cursor: pointer;
    font-size: 20px;
    font-weight: 700;
    background: linear-gradient(90deg, #6a5af9, #d66efd);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-right: 30px;
  }
  
  .live-status {
    display: flex;
    align-items: center;
    margin-right: 20px;
    
    .status-indicator {
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin-right: 8px;
      background: #f44336;
      box-shadow: 0 0 10px #f44336;
      
      &.live {
        background: #f44336;
        box-shadow: 0 0 10px #f44336;
      }
    }
  }
  
  .user-count {
    display: flex;
    align-items: center;
    margin-right: auto;
    
    i {
      margin-right: 5px;
      color: #6a5af9;
    }
  }
  
  .leave-btn {
    border-radius: 20px;
    padding: 8px 15px;
    i {
      margin-right: 5px;
    }
  }
}

.main-content {
  display: flex;
  flex: 1;
  padding: 20px;
  gap: 20px;
  overflow: hidden;
}

.video-section {
  flex: 3;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-container {
  position: relative;
  background: #000;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
  flex: 1;
  
  .video-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    background: #111;
  }
  
  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.7);
    z-index: 10;
    
    .spinner {
      width: 50px;
      height: 50px;
      border: 4px solid rgba(255, 255, 255, 0.1);
      border-top: 4px solid #6a5af9;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 15px;
    }
    
    .loading-text {
      font-size: 18px;
      color: #fff;
    }
  }
  
  .overlay-info {
    position: absolute;
    bottom: 20px;
    left: 20px;
    right: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .viewer-count {
      background: rgba(0, 0, 0, 0.6);
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 14px;
      color: #fff;
      display: flex;
      align-items: center;
      
      i {
        margin-right: 5px;
        color: #6a5af9;
      }
    }
    
    .current-product {
      background: rgba(106, 90, 249, 0.8);
      padding: 6px 15px;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 500;
      color: #fff;
    }
  }
  
  .play-controls {
    position: absolute;
    bottom: 20px;
    right: 20px;
    display: flex;
    gap: 10px;
    
    .control-btn {
      width: 44px;
      height: 44px;
      font-size: 18px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }
  }
}

.product-list {
  background: #1a1c2b;
  border-radius: 12px;
  padding: 15px;
  overflow: hidden;
  
  h3 {
    margin: 0 0 15px 0;
    display: flex;
    align-items: center;
    font-size: 16px;
    color: #d0d0e0;
    
    .el-tag {
      margin-left: 10px;
    }
  }
  
  .products {
    display: flex;
    gap: 15px;
    overflow-x: auto;
    padding-bottom: 10px;
    
    &::-webkit-scrollbar {
      height: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #25283d;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #6a5af9;
      border-radius: 3px;
    }
  }
  
  .product-card {
    min-width: 200px;
    background: #25283d;
    border-radius: 10px;
    overflow: hidden;
    transition: all 0.3s;
    border: 2px solid transparent;
    
    &.active {
      border-color: #6a5af9;
      box-shadow: 0 0 0 3px rgba(106, 90, 249, 0.3);
      transform: translateY(-5px);
    }
    
    img {
      width: 100%;
      height: 120px;
      object-fit: cover;
      background: #333;
    }
    
    .product-info {
      padding: 12px;
      
      .name {
        font-weight: 600;
        margin-bottom: 5px;
        color: #fff;
      }
      
      .price {
        color: #ff6b6b;
        font-weight: 700;
        font-size: 18px;
        margin-bottom: 3px;
      }
      
      .sales {
        font-size: 12px;
        color: #a0a0c0;
      }
    }
  }
}

.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #1a1c2b;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
  
  .chat-header {
    padding: 15px 20px;
    background: linear-gradient(90deg, #25283d, #2d3045);
    font-size: 18px;
    font-weight: 600;
    color: #e0e0e0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #2d3045;
    
    i {
      margin-right: 10px;
      color: #6a5af9;
    }
    
    .el-tag {
      margin-left: 10px;
    }
  }
  
  .chat-messages {
    flex: 1;
    padding: 15px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    
    .message {
      margin-bottom: 15px;
      padding: 12px;
      background: #25283d;
      border-radius: 10px;
      border-left: 3px solid #3a3d5d;
      animation: fadeIn 0.3s ease;
      max-width: 90%;
      
      &.system {
        border-left-color: #6a5af9;
        background: rgba(106, 90, 249, 0.1);
        align-self: center;
        max-width: 80%;
      }
      
      &.chat:not(.system) {
        align-self: flex-start;
      }
      
      &.mine {
        align-self: flex-end;
        background: rgba(56, 98, 189, 0.2);
        border-left-color: #3862bd;
      }
      
      .message-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
        font-size: 13px;
        
        .username {
          font-weight: 600;
          color: #6a5af9;
          
          &.mine {
            color: #5a93ff;
          }
        }
        
        .timestamp {
          color: #7a7a9a;
          font-size: 12px;
        }
      }
      
      .content {
        color: #d0d0e0;
        line-height: 1.4;
        word-break: break-word;
      }
    }
  }
  
  .chat-input {
    padding: 15px;
    border-top: 1px solid #2d3045;
    background: #25283d;
    
    .el-input {
      border-radius: 8px;
      overflow: hidden;
    }

    .el-button {
      &:hover {
        background-color: rgb(27, 27, 27);
      }
    }
  }
}

.live-footer {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background: #1a1c2b;
  border-top: 1px solid #2d3045;
  font-size: 14px;
  color: #888;
  
  div {
    display: flex;
    align-items: center;
    
    i {
      margin-right: 8px;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>